﻿// Necroz project team © <2015> <ArchLord2EMU>
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Author:Sagara
// Date:2015-09-06-23:29

using System;
using System.Diagnostics;
using AL2Login.Database;
using AL2Login.Network;
using AL2Login.Services;
using ArchLord2Commons.IoC;
using ArchLord2Commons.Utils;
using NLog;

namespace AL2Login
{
    class LoginServer : Global
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();
       
        static void Main()
        {
            LogManager.Configuration = Extensions.NLogDefaultConfiguration;

            Console.Title = "ArchLord2EMU | Necroz project team | LoginServer";

            Console.CancelKeyPress += CancelEventHandler;

            AppDomain.CurrentDomain.UnhandledException += UnhandledException;

            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

            var time = Stopwatch.StartNew();

            Register(new DatabaseService());

            Register(new AuthorizeService());

            Register(new GameServerPipeService());

            Register(new NetworkService());

            Log.Info($"Application successfully started at {(time.ElapsedMilliseconds / (float)1000)} seconds");

            time.Stop();

            Initilize();
        }

        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            StopServer();
        }

        private static void CancelEventHandler(object sender, ConsoleCancelEventArgs e)
        {
            StopServer();
        }

        private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            StopServer();

            Log.Error($"Something wrong with {e.ExceptionObject}");

            Console.Read();
        }

        private static void StopServer()
        {
            Log.Info("<----------ServerSuccessfully stoped!---------->");
        }
    }
}
